package org.chen.wordwave.act;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.SignIn;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.user.UserUtils;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Date;

import dalvik.system.DexClassLoader;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Splash extends BaseActivity {
    private static final int START_COUNT = 100;
    private TextView tv_splash_time;
    private int nowMill = 5;
    private static final String PREFS_NAME = "WordMasterPrefs";
    private static final String PRIVACY_POLICY_AGREED = "PrivacyPolicyAgreed";
    private String language;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 100) {
                if (nowMill != 0) {
                    nowMill--;
                    tv_splash_time.setText(getString(R.string.pass) + nowMill + " s");
                    handler.sendEmptyMessageDelayed(START_COUNT, 1000);
                } else {
                    startNewActivity();
                    finish();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isUpdatedVersionAvailable()) {
            loadUpdatedSplashActivity(savedInstanceState);
        } else {
            initializeSplashActivity(savedInstanceState);
        }
        if (WordInit.userInfo.getEmail() != null){
            UserUtils.getCurrentUserNow(getApplicationContext());
        }
        language = WordInit.language;
    }

    private void initializeSplashActivity(Bundle savedInstanceState) {
        if (shouldShowPrivacyPolicy()) {
            showPrivacyPolicyDialog();
        } else {
            handler.sendEmptyMessage(START_COUNT);
        }
    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.splash_act;
    }

    @Override
    public void init() {
        tv_splash_time = findViewById(R.id.tv_splash_time);
        tv_splash_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startNewActivity();
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(START_COUNT);
    }

    private void startNewActivity() {
        if (WordInit.userInfo.getEmail() == null || WordInit.userInfo.getEmail().isEmpty()) {
            startActivity(new Intent(Splash.this, Login.class));
        } else {
            // 检查会员状态
            checkMembershipStatus();
            startActivity(new Intent(Splash.this, Main.class));
        }
    }

    private void checkMembershipStatus() {
        UserInfo currentUser = UserUtils.getCurrentUser(getApplicationContext());
        if (currentUser != null && currentUser.isMember()) {
            Date currentDate = new Date();

            // 检查会员是否过期
            if (currentUser.getMembershipExpiryDate() != null &&
                    currentDate.after(currentUser.getMembershipExpiryDate())) {
                // 会员已过期，更新状态
                currentUser.setMember(false);
                currentUser.setMembershipExpiryDate(null);

                // 如果是订阅会员，清除会员类型
                if (currentUser.getMembershipType() == 2) {
                    currentUser.setMembershipType(0);
                }
                currentUser.save();

                // 同步到服务器
                syncToServer(currentUser);
            }
        }
    }

    private void syncToServer(UserInfo userInfo) {
        ApiService apiService = ApiClient.getClient(this).create(ApiService.class);
        SignIn signIn = new SignIn();
        signIn.setEmail(userInfo.getEmail());
        signIn.setMember(userInfo.isMember());
        signIn.setMembershipType(userInfo.getMembershipType());
        signIn.setPoints(userInfo.getPoints());
        signIn.setMembershipExpiryDate(userInfo.getMembershipExpiryDate() != null ?
                userInfo.getMembershipExpiryDate().getTime() : 0);

        apiService.gift(signIn).enqueue(new Callback<SignIn>() {
            @Override
            public void onResponse(@NonNull Call<SignIn> call, @NonNull Response<SignIn> response) {
                // 处理响应
            }

            @Override
            public void onFailure(@NonNull Call<SignIn> call, @NonNull Throwable t) {
                Log.e("Splash", "Failed to sync membership status", t);
            }
        });
    }

    private boolean shouldShowPrivacyPolicy() {
        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        return !preferences.getBoolean(PRIVACY_POLICY_AGREED, false);
    }

    private void showPrivacyPolicyDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_privacy_policy, null);
        builder.setView(dialogView);

        TextView tvPrivacyPolicyLink = dialogView.findViewById(R.id.tv_privacy_policy_link);
        TextView tv_privacy_policy_link2 = dialogView.findViewById(R.id.tv_privacy_policy_link2);
        Button btnAgree = dialogView.findViewById(R.id.btn_agree);
        Button btnDisagree = dialogView.findViewById(R.id.btn_disagree);

        AlertDialog dialog = builder.create();

        tvPrivacyPolicyLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url;
                if (language.equals("zh")){
                    url = WordInit.zhUser;
                }else {
                    url = WordInit.enUser;
                }
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });
        tv_privacy_policy_link2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url;
                if (language.equals("zh")){
                    url = WordInit.zhPrivacy;
                }else {
                    url = WordInit.enPrivacy;
                }
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });

        btnAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean(PRIVACY_POLICY_AGREED, true);
                editor.apply();
                dialog.dismiss();
                handler.sendEmptyMessage(START_COUNT);
            }
        });

        btnDisagree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    private boolean isUpdatedVersionAvailable() {
        // 检查更新后的资源是否存在
        File dexFile = new File(getExternalFilesDir(null), "resources/classes.dex");
        return dexFile.exists();
    }

    private void loadUpdatedSplashActivity(Bundle savedInstanceState) {
        try {
            File dexFile = new File(getExternalFilesDir(null), "resources/classes.dex");
            File optimizedDir = getDir("dex", Context.MODE_PRIVATE);

            DexClassLoader dexClassLoader = new DexClassLoader(dexFile.getAbsolutePath(), optimizedDir.getAbsolutePath(), null, getClassLoader());
            Class<?> loadedClass = dexClassLoader.loadClass("org.chen.wordwave.act.Splash");
            Object instance = loadedClass.newInstance();

            Method onCreateMethod = loadedClass.getMethod("onCreate", Bundle.class);
            onCreateMethod.invoke(instance, savedInstanceState);
            finish();
        } catch (Exception e) {
            Log.e("Splash",e.toString());
            // 如果加载更新后的类失败，继续使用旧版本的类
            initializeSplashActivity(savedInstanceState);
        }
    }

}

